package com.kedacom.freedomLabel.view.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.Toast;

import com.hard.CardReadHelp;
import com.hard.ReturnValue;
import com.hard.ReturnValueCallback;
import com.hard.TestActivity;
import com.kedacom.freedomLabel.Options;
import com.kedacom.freedomLabel.R;
import com.kedacom.freedomLabel.base.BaseActivity;
import com.kedacom.freedomLabel.databinding.ActivityOperatorControlBinding;
import com.kedacom.freedomLabel.model.DataControlResult;
import com.kedacom.freedomLabel.model.bean.Operator;
import com.kedacom.freedomLabel.model.db.AppDatabase;
import com.kedacom.freedomLabel.model.db.dao.OperatorDao;
import com.kedacom.freedomLabel.view.fragment.ListDataFragment;
import com.kedacom.freedomLabel.viewmodel.OperatorControlViewModel;
import com.kedacom.lego.annotation.ContentView;
import com.kedacom.lego.annotation.OnMessage;
import com.kedacom.lego.annotation.ViewModel;
import com.kedacom.lego.fast.validation.RegexTemplate;
import com.kedacom.lego.message.LegoMessageManager;

import java.lang.ref.WeakReference;
import java.util.Random;
import java.util.regex.Pattern;


@ContentView(R.layout.activity_operator_control)
@ViewModel(OperatorControlViewModel.class)
public class OperatorControlActivity extends BaseActivity<ActivityOperatorControlBinding, OperatorControlViewModel> {

    Operator mSelectedItem = null;
    private CardReadHelp mReadCardHelp;

    @SuppressLint("HandlerLeak")
    private Handler mScaleHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                if(msg.obj.toString().contains("&")){
                    String[] CardNum= msg.obj.toString().split("&");
                    mBinding.evName.setText(CardNum[1]);
                    mBinding.evNumber.setText(CardNum[0]);
                    openEditLayout();
                }else {
                    showToast(msg.obj.toString(), TOAST_WARNING);
                }
        }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mReadCardHelp =CardReadHelp.getSingleton(); // new CardReadHelp();
        closeEditLayout();
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        OperatorDao dao = AppDatabase.getInstance().operatorDao();
        ListDataFragment<Operator> fragment = ListDataFragment.newInstance(dao);
        transaction.add(mBinding.recyclerContainer.getId(), fragment);
        transaction.commit();
    }

    @OnMessage(value = Options.MSG_SELECT_ITEM, discard = true)
    public void receiveItemClickMessage(Operator item) {
        closeEditLayout();
        mSelectedItem = item;
        mBinding.evName.setText(item.name);
        mBinding.evNumber.setText(item.cardNumber);
        mBinding.evRemark.setText(item.remark);
        if (item.name != null) {
            mBinding.evName.setSelection(item.name.length());
        }
        if (item.cardNumber != null) {
            mBinding.evNumber.setSelection(item.cardNumber.length());
        }
        if (item.remark != null) {
            mBinding.evRemark.setSelection(item.remark.length());
        }
    }

    /**
     * 接收数据更新结果通知
     *
     * @param result 结果
     */
    @OnMessage(value = Options.MSG_SAVE_ITEM_RESULT, discard = true)
    public void receiveDataSaveResult(DataControlResult<Operator> result) {
        if (result.result) {
            closeEditLayout();
            mSelectedItem = result.data;
        }
    }

    /**
     * 接收数据删除结果通知
     *
     * @param result 结果
     */
    @OnMessage(value = Options.MSG_DELETE_ITEM_RESULT, discard = true)
    public void receiveDataDeleteResult(DataControlResult<Operator> result) {
        if (result.result) {
            mSelectedItem = null;
            clear();
        }
    }

    /**
     * 接收新增数据结果通知
     *
     * @param result 结果
     */
    @OnMessage(value = Options.MSG_ADD_ITEM_RESULT, discard = true)
    public void addItemComplete(DataControlResult<Operator> result) {
        if (result.result) {
            closeEditLayout();
        }
    }

    @OnMessage(value = Options.MSG_ADD_EXISTS_RESULT, discard = true)
    public void exitItemComplete(DataControlResult<Operator> result) {
        if (result.result) {
            showToast(getString(R.string.alraad_opertor_name)+"名字："+result.data.name, TOAST_WARNING);
            closeEditLayout();
        }
    }

    @OnMessage(value = Options.MSG_RECOVERY_ITEM_DETAIL, discard = true)
    public void recoveryDetailLayout() {
        clear();
        closeEditLayout();
    }

    // 保存
    public void onSaveItemButtonClick(View view) {
        beep();
        String name = mBinding.evName.getText().toString();
        String number = mBinding.evNumber.getText().toString();
        if (!Pattern.compile(RegexTemplate.NOT_EMPTY).matcher(name).matches()) {
            showToast(getString(R.string.validation_empty_name), TOAST_WARNING);
            return;
        }
        if (!Pattern.compile(RegexTemplate.NOT_EMPTY).matcher(number).matches()) {
            showToast(getString(R.string.validation_empty_number), TOAST_WARNING);
            return;
        }
        Object tag = mBinding.save.getTag();
        if (tag != null) {
            mViewModel.updateOperator(mSelectedItem);
        } else {
            mViewModel.saveOperator();
        }
    }

    // 删除
    public void onDeleteItemButtonClick(View view) {
        beep();
        showDialog("是否删除", "删除", (dialog, which) -> {
            beep();
            LegoMessageManager.getInstance().sendEmptyMessage(Options.MSG_DELETE_ITEM);
            dialog.dismiss();
        });
    }

    // 增加
    public void onAddItemButtonClick(View view) {
        beep();
        showDialog("是否通过读取用户卡片添加操作员？", "读取卡片", "手动添加", (dialog, which) -> {
            beep();
            if (which == DialogInterface.BUTTON_POSITIVE) {
                dialog.dismiss();
                // TODO: 2020/6/5 执行读卡并写入操作员
//                if (mReadCardHelp != null){
//                    mReadCardHelp.cancelReadCard(null);
//                }
                    mMisc.beep();
                    mReadCardHelp.readCardId(new ReturnValueCallback() {
                        @Override
                        public void run(ReturnValue result) {
                            if (result != null) {
                                Message message = Message.obtain();
                                message.what = 0;
                                String msg;
                                Object tag = result.getTag();
                                if (tag != null)
                                    msg = tag.toString();
                                else
                                    msg = "未知错误";
                                message.obj = msg;
                                mScaleHandler.sendMessage(message);
                            }
                        }
                    });

            } else if (which == DialogInterface.BUTTON_NEGATIVE) {
                dialog.dismiss();
                openEditLayout();
                clear();
            }
        });
    }

    private void clear() {
        mBinding.save.setTag(null);
        mBinding.evName.setText(null);
        mBinding.evNumber.setText(null);
        mBinding.evRemark.setText(null);
        mBinding.evName.setSelection(0);
        mBinding.evNumber.setSelection(0);
        mBinding.evRemark.setSelection(0);
    }

    @Override
    protected void onStop() {
        super.onStop();
//        if (mReadCardHelp != null){
//            mReadCardHelp.cancelReadCard(null);}
    }

    // 编辑
    public void onEditItemButtonClick(View view) {
        beep();
        if (mSelectedItem != null) {
            openEditLayout();
            // 标识编辑
            mBinding.save.setTag(mSelectedItem.uuid);
        }
    }

    // 清除
    public void onClearButtonClick(View view) {
        beep();
        mBinding.evName.setText(null);
        mBinding.evNumber.setText(null);
        mBinding.evRemark.setText(null);
        mBinding.evName.setSelection(0);
        mBinding.evNumber.setSelection(0);
        mBinding.evRemark.setSelection(0);
    }

    // 返回
    public void onCancelEditButtonClick(View view) {
        beep();
        closeEditLayout();
        // 标识新增
        mBinding.save.setTag(null);
    }

    // 退出
    public void onBackClick(View view) {
        beep();
        finish();
    }

    private void closeEditLayout() {
        mBinding.evName.setEnabled(false);
        mBinding.evNumber.setEnabled(false);
        mBinding.evRemark.setEnabled(false);
        mBinding.controlAddLayout.setVisibility(View.VISIBLE);
        mBinding.controlSaveLayout.setVisibility(View.GONE);
    }

    private void openEditLayout() {
        mBinding.evName.setEnabled(true);
        mBinding.evNumber.setEnabled(true);
        mBinding.evRemark.setEnabled(true);
        mBinding.controlAddLayout.setVisibility(View.GONE);
        mBinding.controlSaveLayout.setVisibility(View.VISIBLE);
    }
}